// pages/index/index.js

const app = getApp()
import _ from './../../utils/lodash.js';
import util from './../../utils/util.js';
import config from './../../utils/config.js';
let permissions = [];
if (app.globalData.userInfo) {
	permissions = app.globalData.userInfo.permissions
}
const find = _.find;

Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		meter_maintenance: Boolean(find(permissions, {
			name: 'meter_maintenance'
		})),
		concentrator_tool: Boolean(find(permissions, {
			name: 'concentrator_tool'
		})),
		concentrator_management: Boolean(find(permissions, {
			name: 'concentrator_management'
		})),
		concentrator_operation: Boolean(find(permissions, {
			name: 'concentrator_operation'
		})),
		bluetooth: false,
		camera: false,
		userLocation: false,
		writePhotosAlbum: false,
		index: 0,
		companyIndex: [0],
		showMyPicker: false,
		management_companies: app.globalData.userInfo?[{id:"null",name:'请选择'},...app.globalData.userInfo.management_companies].reduce((prev, cur, index, arr) => {
			console.log(prev)
			// console.log(cur)
			if (cur.id) {
				prev.push(cur);
				return prev
			} else {
				return prev
			}
		}, []):[],

	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad(options) {
		if (app.globalData.userInfo) {
			permissions = app.globalData.userInfo.permissions;
			this.setData({
				meter_maintenance: Boolean(find(permissions, {
					name: 'meter_maintenance'
				})),
				concentrator_tool: Boolean(find(permissions, {
					name: 'concentrator_tool'
				})),
				concentrator_management: Boolean(find(permissions, {
					name: 'concentrator_management'
				})),
				concentrator_operation: Boolean(find(permissions, {
					name: 'concentrator_operation'
				})),
				username: app.globalData.userInfo.username,
			})
		}
		this.getAuth()
	},
	toggleShowMyPicker() {
		this.setData({
			showMyPicker: !this.data.showMyPicker
		})
	},
	bindChangeMyPicker(e) {

		const val = e.detail.value
		console.log(val)
		this.setData({
			companyIndex: val,
		})
	},
	getAuth: function () {
		wx.getSetting({
			success: res => {
				console.log(res.authSetting)
				this.setData({
					bluetooth: res.authSetting['scope.bluetooth'],
					// camera: res.authSetting['scope.camera'],
					// writePhotosAlbum: res.authSetting['scope.writePhotosAlbum'],
					// userLocation: res.authSetting['scope.userLocation']
				})
			}
		})
	},
	getBluetooth: function () {
		wx.authorize({
			scope: 'scope.bluetooth',
			success: () => {
				this.getAuth()
			}
		})
	},
	getWritePhotosAlbum: function () {
		wx.authorize({
			scope: 'scope.writePhotosAlbum',
			success: () => {
				this.getAuth()
			}
		})
	},

	getCamera: function () {
		wx.authorize({
			scope: 'scope.camera',
			success: () => {
				this.getAuth()
			}
		})
	},
	goScanMeter: function () {
		//console.log('ds', e.currentTarget.dataset.item)
		// const ds= e.currentTarget.dataset.item
		console.log('goInstall')
		const that = this;
		wx.showActionSheet({
			itemList: ['扫描水表二维码/条形码', '手动输入水表号'],
			success(res) {
				console.log(res.tapIndex)
				if (res.tapIndex === 0) {
					wx.scanCode({
						scanType: 'barCode',
						success(res) {
							console.log(res)
							let number = res.result;
							if (res.result.length!==10&&res.result.length!==12) {
								util.toastError('水表号需为10/12位')
							} else {
								that.getMeter(res.result)
							}



						},
						fail: function (res) {
							util.toastError('识别失败,请检查')
							console.log('识别失败')
							console.log(res)
						}
					})
				} else if (res.tapIndex === 1) {
					console.log('手动输入')
					wx.showModal({
						title: '请输入水表号',
						editable: true,
						content: '',
						success(res) {
							if (res.confirm) {
								console.log('用户点击确定')
								console.log(res.content)
								if (res.content.length !== 10&&res.content.length !== 12) {
									util.toastError('水表号需为10/12位')
								} else {
									that.getMeter(res.content)
								}
							} else if (res.cancel) {
								console.log('用户点击取消')
							}
						}
					})

				}
			},
			fail(res) {
				console.log(res.errMsg)
			}
		})



	},


	goIndex: function () {
		console.log('goIndex')
		wx.navigateTo({
			url: '/pages/index/index',
		})
	},
	goLogs: function () {
		console.log('goIndex')
		wx.navigateTo({
			url: '/pages/log_list/list',
		})
	},
	goTest: function () {
		console.log('goIndex')
		wx.navigateTo({
			url: '/pages/test_list/list',
		})
	},
	goMap: function () {
		console.log('goIndex')
		wx.switchTab({
			url: '/pages/map/list',
		})
	},
	goAlarm: function () {
		console.log('goIndex')
		wx.switchTab({
			url: '/pages/alarm_list/list',
		})
	},
	goList: function () {
		wx.navigateTo({
			url: '/pages/list/list',
		})
	},
	goSwap: function () {
		wx.navigateTo({
			url: '/pages/swap/swap',
		})
	},
	goInstall: function () {
		//console.log('ds', e.currentTarget.dataset.item)
		// const ds= e.currentTarget.dataset.item
		console.log('goInstall')
		const that = this;
		wx.showActionSheet({
			itemList: ['扫描集中器二维码/条形码', '手动输入集中器号'],
			success(res) {
				console.log(res.tapIndex)
				if (res.tapIndex === 0) {
					wx.scanCode({
						scanType: 'barCode',
						success(res) {
							console.log(res)
							let number = res.result;
							if (res.result.length !== 8) {
								util.toastError('条形码格式错误')
							} else {
								that.getConcerntor(res.result)
							}



						},
						fail: function (res) {
							util.toastError('识别失败,请检查')
							console.log('识别失败')
							console.log(res)
						}
					})
				} else if (res.tapIndex === 1) {
					console.log('手动输入')
					wx.showModal({
						title: '请输入集中器号',
						editable: true,
						content: '',
						success(res) {
							if (res.confirm) {
								console.log('用户点击确定')
								console.log(res.content)
								if (res.content.length !== 8) {
									util.toastError('集中器号长度错误')
								} else {
									that.getConcerntor(res.content)
								}
							} else if (res.cancel) {
								console.log('用户点击取消')
							}
						}
					})

				}
			},
			fail(res) {
				console.log(res.errMsg)
			}
		})



	},
	goAddOrDel: function (e) {
		//console.log('ds', e.currentTarget.dataset.item)
		const type= e.currentTarget.dataset.type
		console.log('goInstall')
		const that = this;
		wx.showActionSheet({
			itemList: ['扫描集中器二维码/条形码', '手动输入集中器号'],
			success(res) {
				console.log(res.tapIndex)
				if (res.tapIndex === 0) {
					wx.scanCode({
						scanType: 'barCode',
						success(res) {
							console.log(res)
							let number = res.result;
							if (res.result.length !== 8) {
								util.toastError('条形码格式错误')
							} else {
								that.getExitConcerntor(res.result,type)
							}



						},
						fail: function (res) {
							util.toastError('识别失败,请检查')
							console.log('识别失败')
							console.log(res)
						}
					})
				} else if (res.tapIndex === 1) {
					console.log('手动输入')
					wx.showModal({
						title: '请输入集中器号',
						editable: true,
						content: '',
						success(res) {
							if (res.confirm) {
								console.log('用户点击确定')
								console.log(res.content)
								if (res.content.length !== 8) {
									util.toastError('集中器号长度错误')
								} else {
									that.getExitConcerntor(res.content,type)
								}
							} else if (res.cancel) {
								console.log('用户点击取消')
							}
						}
					})

				}
			},
			fail(res) {
				console.log(res.errMsg)
			}
		})



	},
	getExitConcerntor: function (number,type) {
		const that = this
		this.setData({
			number: number
		})
		wx.request({
			url: `${config.prefix}/concentrators`,
			header: {
				Authorization: `Bearer ${app.globalData.userInfo.token}`
			},
			method: 'GET',
			data: {
				number: number
			},
			success: function (res) {
				if (res.statusCode === 200) {
					console.log('获取成功');
					if (res.data.data.length === 1) {
						if(type==='add'){
							wx.navigateTo({
								url: `/pages/addOrdel/detail?number=${number}&type=${type}&editable=false`,
							})
						}else if(type==='del'){
							wx.navigateTo({
								url: `/pages/addOrdel/detail?number=${number}&type=${type}&editable=false`,
							})
						}else if(type==='swap'){
							wx.navigateTo({
								url: `/pages/addOrdel/detail?number=${number}&type=${type}&editable=false`,
							})
						}else if(type==='reset'){
							wx.navigateTo({
								url: `/pages/addOrdel/detail?number=${number}&type=${type}&editable=false`,
							})
						} else if(type==='sync'){
							wx.navigateTo({
								url: `/pages/addOrdel/detail?number=${number}&type=${type}&editable=false`,
							})
						}

					} else {
						util.toastError(`请先在系统中添加集中器${number}`)
						// that.toggleShowMyPicker()
					}
				} else {
					util.converErrorCodeToMsg(res)
				}

			}
		})
	},
	getConcerntor: function (number) {
		const that = this
		this.setData({
			number: number
		})
		wx.request({
			url: `${config.prefix}/concentrators`,
			header: {
				Authorization: `Bearer ${app.globalData.userInfo.token}`
			},
			method: 'GET',
			data: {
				number: number
			},
			success: function (res) {
				if (res.statusCode === 200) {
					console.log('获取成功');
					if (res.data.data.length === 1) {
						wx.navigateTo({
							url: `/pages/list_detail/detail?number=${number}&editable=true`,
						})
					} else {
						console.log('系统中没有，自动添加')
						// util.toastError(`请先在系统中添加集中器${number}`)
						that.toggleShowMyPicker()
					}
				} else {
					util.converErrorCodeToMsg(res)
				}

			}
		})
	},
	getMeter: function (number) {
		const that = this
		this.setData({
			number: number
		})
		wx.request({
			url: `${config.prefix}/meters/${number}`,
			header: {
				Authorization: `Bearer ${app.globalData.userInfo.token}`
			},
			method: 'GET',
			success: function (res) {
				if (res.statusCode === 200) {
					console.log('获取成功');
					if (res.data.data.number) {
						wx.navigateTo({
							url: `/pages/meter_detail/detail?meter_number=${number}`,
						})
					} else {
						console.log('系统中没有该水表')
						wx.showToast({
							title: '系统中没有该水表',
							icon: 'none'
						})
						// util.toastError(`请先在系统中添加集中器${number}`)
					}
				} else {
					util.converErrorCodeToMsg(res)
				}

			}
		})
	},
	bindtapLogout: function () {
		console.log('tap')
		wx.showModal({
			title: '提示',
			content: '确定要退出吗?',
			success(res) {
				if (res.confirm) {
					console.log('用户点击确定');

					wx.request({
						url: `${config.prefix}/logout`,
						header: {
							Authorization: `Bearer ${app.globalData.userInfo.token}`
						},
						method: 'POST',
						success: function (res) {
							if (res.statusCode === 200) {
								wx.clearStorage()
								wx.showToast({
									title: '退出成功',
									icon: 'success'
								})
								setTimeout(function () {
									wx.reLaunch({
										url: '/pages/login/login'
									})
								}, 500)
							}
						}

					})
					setTimeout(function () {
						wx.reLaunch({
							url: '/pages/login/login'
						})
					}, 1000)
				} else if (res.cancel) {
					console.log('用户点击取消')
				}
			}
		})


	},
	addConcentrator: function () {
		const that = this
		if(this.data.companyIndex[0]==0){
			wx.showToast({
				title: '请先选择分站',
				icon: 'none'
			})
			return
		}
		wx.request({
			url: `${config.prefix}/concentrators`,
			header: {
				Authorization: `Bearer ${app.globalData.userInfo.token}`
			},
			method: 'POST',
			data: {
				number: this.data.number,
				company_id: this.data.management_companies[this.data.companyIndex[0]].id,
			},
			success: function (res) {
				if (res.statusCode === 200) {
					console.log('添加成功');
					that.toggleShowMyPicker()
					wx.navigateTo({
						url: `/pages/list_detail/detail?number=${that.data.number}&editable=true`,
					})
				} else {
					util.converErrorCodeToMsg(res)
				}

			}
		})
	},
	goPicture: function () {
		wx.chooseMedia({
			count: 1,
			mediaType: ['image'],
			sourceType: ['album'],
			success: res => {
				console.log(res)
				wx.navigateTo({
					url: '/pages/picture/picture?imageUrl=' + res.tempFiles[0].tempFilePath,
				})
			}
		})
	},
	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady() {

	},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow() {

	},

	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide() {

	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload() {

	},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh() {

	},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom() {

	},

	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage() {

	}
})